﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Telerik.Windows.Controls;
using System.Threading;
using WCFDynamicProxyLibrary.DynamicProxy;
using Broker.Model;
using NHibernate;
using System.ComponentModel;
using BrokerBase.Lib.Client;
using Broker.Update;
using Broker.Comm;
using System.Text.RegularExpressions;
using System.ServiceModel;
using Broker.DataService;

namespace Broker
{
    /// <summary>
    /// Interaction logic for RegisterForm.xaml
    /// </summary>
    public partial class RegisterForm
    {
        

        private BackgroundWorker worker = new BackgroundWorker();

        private LicenseInfo licInfo;
        private string activeCode;//当前输入的注册码
        private ActiveResult result;

        private IList<string> urls;

        private const string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

        public Action<bool> CallBack;

        RegistrantInfo registrantInfo;
        TerminalInfo terminalInfo;
        

        public RegisterForm(LicenseInfo licInfo)
        {
            this.licInfo = licInfo;
            InitializeComponent();

            urls = new List<string>() { AppGlobal.ClientCfg.ServerUrl1, AppGlobal.ClientCfg.ServerUrl2 };

            Loaded += new RoutedEventHandler(RegisterForm_Loaded);

            this.PreviewClosed += new EventHandler<WindowPreviewClosedEventArgs>(RegisterForm_PreviewClosed);
        }

        void RegisterForm_PreviewClosed(object sender, WindowPreviewClosedEventArgs e)
        {
            if (worker.IsBusy)
            {
                MessageBox.Show("正在进行产品注册，请等待..","提示");
                e.Cancel = true;
            }
        }



        public RegisterForm(LicenseInfo licInfo, ContentControl Owner):this(licInfo)
        {
            this.Owner = Owner;
        }

        void RegisterForm_Loaded(object sender, RoutedEventArgs e)
        {

            SetCurrentLicInfo();//设置注册名和推荐人(如果有的话)

            worker.DoWork += new DoWorkEventHandler(worker_DoWork);

            worker.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

        }


        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            ChannelFactory<IDataService> factory = AppGlobal.CreateDataServiceFactory();

            try
            {
                factory.Open();
                IDataService ser = factory.CreateChannel();

                InvokeStatus("正在注册...请等待");

                string tmp = ser.Register(registrantInfo.GetData(), terminalInfo.GetData(), activeCode);

                result = Newtonsoft.Json.JsonConvert.DeserializeObject<ActiveResult>(tmp);

                factory.Close();
            }
            catch (Exception ex)
            {
                factory.Abort();
                InvokeStatus("注册时发生错误："+ex.Message);
                AppGlobal.Log.Error("注册错误", ex);
            }
        }


        private void InvokeStatus(string text)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.txtStatus.Text =text;
            }));
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ISession sess = null;

            try
            {

                if (result.IsSuccess)
                {
                    licInfo.PresenterName = result.PresenterName;//客户端录入的推荐人可能不一定正确
                    licInfo.UserName = txtEmail.Text.Trim();
                    licInfo.LicenseCode = result.LicenseCode;

                    RegInfo reg = new RegInfo();
                    reg.ActiveCode = activeCode;
                    reg.Period = result.Period;
                    reg.BeginTime = result.BeginTime.Value;
                    reg.EndTime = result.EndTime.Value;
                    reg.FingerprintOfDISK = LicenseInfo.CalcFingerprint(registrantInfo.UserName, reg.ActiveCode, reg.BeginTime, reg.EndTime, reg.Period, licInfo.DISKSerialNo);
                    reg.FingerprintOfMAC = LicenseInfo.CalcFingerprint(registrantInfo.UserName, reg.ActiveCode, reg.BeginTime, reg.EndTime, reg.Period, licInfo.MACSerialNo);
                    reg.FingerprintOfMB = LicenseInfo.CalcFingerprint(registrantInfo.UserName, reg.ActiveCode, reg.BeginTime, reg.EndTime, reg.Period, licInfo.MBSerialNo);

                    reg.LicenseType = result.LicenseType;
                    licInfo.RegInfos.Add(reg);

                    try
                    {

                        LicenseInfo.Save(licInfo);

                        SysUser user = new SysUser();
                        user.Name = licInfo.UserName;
                        user.InvitedCodeQty = result.InvitedCodeQty;
                        user.Password = string.Empty;

                        txtPresenterName.Text = result.PresenterName;

                        sess = AppGlobal.HbmSessionFactory.OpenSession();

                        SysUser.CreateUser(user, sess);

                        AppGlobal.CurrentUser = user;

                        DataContext = user;

                        AppGlobal.DataWCF.User = user;
                        AppGlobal.DataWCF.ImmediateRun();

                        MessageBox.Show("注册成功!");

                        txtStatus.Text = "注册成功";

                        if (CallBack != null)
                            CallBack(true);

                        Close();
                    }
                    catch (Exception ex)
                    {
                        txtStatus.Text = null;
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        if (sess != null)
                            sess.Close();
                    }
                }
                else
                {
                    MessageBox.Show(result.Description);
                    txtStatus.Text = result.Description;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                btnConfirm.IsEnabled = true;
                btnExit.IsEnabled = true;
            }
        }

        /// <summary>
        /// 连接服务器，输入激活码，注册产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            activeCode = txtActiveCode.Text.Trim().ToUpper();

            if (!worker.IsBusy)
            {

                if (Verify())
                {
                    btnConfirm.IsEnabled = false;
                    btnExit.IsEnabled = false;

                    txtStatus.Text = "正在连接服务器,可能需要几分钟时间。请等待...";

                    registrantInfo = LicenseInfo.GetInstance().CreateRegistrantInfo();

                    registrantInfo.UserName = txtEmail.Text.Trim();
                    registrantInfo.PresenterName = txtPresenterName.Text.Trim();

                    terminalInfo = ClientUtil.CreateTerminalInfo();

                    worker.RunWorkerAsync();
                }
            }
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void SetCurrentLicInfo()
        {
            //如果已经注册过，就直接从licinfo中取出userName,并且锁定文本框
            if(!string.IsNullOrEmpty( licInfo.UserName))
            {
                
                txtEmail.Text = licInfo.UserName;
                txtEmail.IsReadOnly = true;
                txtPresenterName.IsReadOnly = true;

            }
            txtPresenterName.Text = licInfo.PresenterName;


        }

        //验证
        private bool Verify()
        {
            if (string.IsNullOrEmpty(txtEmail.Text.Trim()))
            {
                MessageBox.Show("邮箱地址不能为空");
                return false;
            }

            if (string.IsNullOrEmpty(activeCode))
            {
                MessageBox.Show("注册码不能为空!");
                return false;
            }

            else
            {
                Regex re = new Regex(strRegex);

                if(!re.IsMatch(txtEmail.Text.Trim()))
                {
                    MessageBox.Show("邮件地址格式不正确!");
                    return false;
                }
            }

            if (activeCode.Length != 29 || activeCode.Substring(5, 1) != "-" || activeCode.Substring(11, 1) != "-" || activeCode.Substring(17, 1) != "-" || activeCode.Substring(23, 1) != "-")
            {
                MessageBox.Show("请按照xxxxx-xxxxx-xxxxx-xxxxx的格式输入25位注册码!");
                return false;
            }

            return true;
        }
    }
}
